package 网络编程.课后作业;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 5)、使用基于UDP的Java Socket编程，完成在线咨询功能：
 * 1)客户向咨询人员咨询。
 * 2)咨询人员给出回答。
 * 3)客户和咨询人员可以一直沟通，直到客户发送bye给咨询人员。
 */
public class M5 {
    public static void main(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket(6666);
        while (true){

            //准备接收包裹
            byte[] bytes = new byte[1024];
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
            socket.receive(packet); //阻塞接收包裹

            //断开连接 bye
            byte[] data = packet.getData();
            String receiveData = new String(data,0,data.length);

            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

class UdpSer{
    public static void main(String[] args) throws IOException {

        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据：控制台读System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String data = reader.readLine();
        byte[] datas = data.getBytes();
        DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("192.168.1.1",6666));

        socket.send(packet);

        socket.close();


    }
}
